package zxj.spay.modular.data.ctrl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import zxj.spay.base.Context;
import zxj.spay.base.Result;
import zxj.spay.entity.Stream;
import zxj.spay.entity.Type;
import zxj.spay.entity.User;
import zxj.spay.modular.data.service.DataService;
import zxj.spay.util.DateUtil;
/**
 * 数据产生部分
 * @author 朱小杰
 * 日期:2016-05-09
 */
@Controller
@RequestMapping("/data")
public class DataCtrl extends Context{
	/**
	 * 处理所有数据产生的日志
	 */
	public final static Logger LOG = Logger.getLogger(DataCtrl.class);
	@Resource
	private DataService dataService;

	/**
	 * 跳转到增加类型页面
	 * @return
	 */
	@RequestMapping("/addType.htm")
	public String addTypePage(){
		return "/WEB-INF/view/newType.ftl";
	}
	
	/**
	 * 保存一笔收支流水
	 * @param stream
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/addStream.ajax")
	public Result addStream(Stream stream,String sUseTime,HttpServletRequest request){
		try{
			Date useTime = DateUtil.parseDate(sUseTime, "yyyy-MM-dd");
			stream.setUseTime(useTime);
		}catch(Exception e){
			LOG.debug("用户填写的使用日期不是一个正确的格式，无法提交流水");
			return new Result(Result.WARN,"日期格式不正确");
		}
		int user_id = getUser(request).getId();
		User user = new User();
		user.setId(user_id);
		stream.setUser(user);
		Result result = dataService.saveStream(stream);
		return result;
		
	}
	
	/**
	 * 保存一个类型
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/addType.ajax")
	public Result addType(Type type,HttpServletRequest request){
		User user = getUser(request);
		Result result = dataService.addType(type,user.getId());
		return result;
	}
	
	/**
	 * 跳转到新增流水页面
	 * @return
	 */
	@RequestMapping("/addStream.htm")
	public String addStreamPage(){
		return "/WEB-INF/view/newStream.ftl";
	}
	
	/**
	 * 根据状态，获取该状态的类型
	 * @param status  0收入，1 支出
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getTypeByStatus.ajax")
	public List<Type> getTypeByStatus(int status,HttpServletRequest request){
		int user_id = getUser(request).getId();
		return dataService.getTypeByStatus(status,user_id);
	}
}
